package sub3;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.print.attribute.standard.MediaSize.ISO;
import javax.xml.crypto.Data;

import sub2.Server;

/**
 * Handles connections with clients who want to search for a file
 * @see Client
 * @author Magali Moulin, Pierre Labiausse
 * @version 3
 */
public class RequestHandler extends Thread {

	private DatagramPacket dp;
	private Client client;
	
	/**
	 * Constructor of this class 
	 * @param dp : DatagramPacket received with a priori the search request
	 * @param client: keeps the state centralized
	 */
	public RequestHandler(DatagramPacket dp, Client client){
		this.dp = dp;
		this.client = client;
	}
	
	/**
	 * Action of the thread: read the data sent by the client,recognize the type of message received and answer to the client
	 */
	public void run(){
		// Get the message
		String msg = null;
		msg = new String(dp.getData(), 0, dp.getLength());
		StringTokenizer st = new StringTokenizer(msg);
		String command = st.nextToken();
		String id = st.nextToken();
		int sharingPortPeer= Integer.parseInt(st.nextToken());
		// If this is a request that does not come from us
		if(command.equals("request") && ! id.equals(""+client.getIdRequest())){
			String request = st.nextToken();
			System.out.println("Request received with id "+id+" for request "+request+"|");
			ArrayList<String> response = new ArrayList<String>();
			// Do we have corresponding files ?
			System.out.println(request.equals("toto"));
			for(String filename : client.getSharedFiles()){
				if(filename.equals(request)){
					System.out.println(filename);
					response.add(filename);
				}
			}
			System.out.println("Number of responses : "+response.size());
			// If yes, send them to the peer
			if(response.size()>0){
				String _response = "response ";
				_response += id;
				_response += " "+client.getSharingPort();
				for(String filename : response){
					_response += " "+filename;
				}
				DatagramPacket dp2 = new DatagramPacket(_response.getBytes(), _response.getBytes().length, dp.getAddress(), sharingPortPeer);
				try {
					System.out.println("Send back response : "+_response);
					DatagramSocket socket= new DatagramSocket();
					socket.send(dp2);
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
